﻿using DevelopAssistant.Service;
using ICSharpCode.WinFormsUI.Controls;
using ICSharpCode.WinFormsUI.Controls.NTimeLine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace DevelopAssistant.Core.Tabs
{
    public partial class TodoListManagerTab : ICSharpCode.WinFormsUI.Docking.DockContent
    {
        int TotalRecords = 0;

        MainForm mainForm = null;

        TodoManager.ITodoService serviece = new TodoManager.TodoServiceImpl();

        delegate int Delegate_Page_BindData();

        public TodoListManagerTab()
        {
            InitializeComponent();
            InitializeControls();
        }

        public TodoListManagerTab(MainForm mainForm) : this()
        {
            this.mainForm = mainForm;
        }

        private void InitializeControls()
        {
            comboBoxDeleteState.Items.AddRange(new string[] { "全部", "未删除", "已删除" });
            comboBoxDeleteState.SelectedIndex = 0;
            comboBoxImportState.Items.AddRange(new string[] { "全部","进行中","已作废", "已完成" });
            comboBoxImportState.SelectedIndex = 0;
            dataGridView1.DatetimeFormat = AppSettings.DateTimeFormat;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.LostFocus += DataGridView1_LostFocus;
            dataGridView1.RowPostPaint += DataGridView1_RowPostPaint;
        }

        private void DataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                //int deleteSign = Convert.ToInt32(((System.Data.DataRowView)dataGridView1.Rows[e.RowIndex].DataBoundItem)["DeleteSign"]);
                //if (deleteSign == 0)
                //    return;               
            }
        } 
        
        private void DataGridView1_DataBindComplete(object sender,EventArgs e)
        {
            if (this.InvokeRequired)
                dataGridView1.Invoke(new MethodInvoker(delegate ()
                {
                    PremityGridView();
                }));
            else
                PremityGridView();
        }

        private void DataGridView1_LostFocus(object sender, EventArgs e)
        {
            dataGridView1.CancelEdit();
        }

        private Color deleteRowForeColor = System.Drawing.SystemColors.ControlDarkDark;
        private Color deleteRowBackColor = System.Drawing.SystemColors.ControlLight;

        private void PremityGridView()
        {
            var cellStyleFont = dataGridView1.DefaultCellStyle.Font;
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                int deleteSign = Convert.ToInt32(((System.Data.DataRowView)row.DataBoundItem)["DeleteSign"]);
                if (deleteSign == 0)
                    continue;
                //row.DefaultCellStyle.Font = new System.Drawing.Font(cellStyleFont, System.Drawing.FontStyle.Strikeout);
                row.DefaultCellStyle.ForeColor = deleteRowForeColor;
                row.DefaultCellStyle.BackColor = deleteRowBackColor;
            }
        }

        public void TodoListDataBind(out int totalRecords)
        {
            Delegate_Page_BindData d = new Delegate_Page_BindData(BindPagerData);
            totalRecords = d.Invoke();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            pager1.PageCurrent = 1;
            pager1.Bind();
        }

        private int pager1_EventPaging(ICSharpCode.WinFormsUI.Controls.EventPagingArgs e)
        {
            TodoListDataBind(out TotalRecords);
            return TotalRecords;
        }

        private int BindPagerData()
        {
            string strFeilds = "";
            string strWhere = "";
            string strOrder = "";

            strWhere = "1=1";
            int selectedItemType = 0;
            int selectedDeleteSign = 0;
            string txtkeyword = string.Empty;
            if (dataGridView1.InvokeRequired)
            {
                dataGridView1.Invoke(new MethodInvoker(delegate ()
                {
                    txtkeyword = this.textBox1.Text + "";
                    selectedItemType = this.comboBoxImportState.SelectedIndex - 1;
                    selectedDeleteSign = this.comboBoxDeleteState.SelectedIndex - 1;
                    
                }));
            }
            else
            {
                txtkeyword = this.textBox1.Text + "";
                selectedItemType = this.comboBoxImportState.SelectedIndex - 1;
                selectedDeleteSign = this.comboBoxDeleteState.SelectedIndex - 1;
            }

            txtkeyword = txtkeyword.Trim();

            if (selectedDeleteSign > -1)
            {
                strWhere += " and DeleteSign = '" + selectedDeleteSign + "'";
            }
            if (selectedItemType > -1)
            {
                switch (selectedItemType)
                {
                    case 0://进行中
                        selectedItemType = 1;
                        break;
                    case 1://已作废
                        selectedItemType = 5;
                        break;
                    case 2://已完成
                        selectedItemType = 6;
                        break;
                }
                strWhere += " and Timeliness = '" + selectedItemType + "'";
            }
            if (!string.IsNullOrEmpty(txtkeyword))
            {
                strWhere += " and ( Name='"+ txtkeyword + "' or Title='"+ txtkeyword + "' )";
            }

            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    pager1.Enabled = false;
                    toolStrip1.Enabled = false;
                }));
            }
            else
            {
                pager1.Enabled = false;
                toolStrip1.Enabled = false;
            }

            NORM.Entity.PageLimit pageLimit = new NORM.Entity.PageLimit();
            pageLimit.PageIndex = pager1.PageCurrent;
            pageLimit.PageSize = pager1.PageSize;
            System.Data.DataTable dataTable = serviece.GetTodoListData(strFeilds, strWhere, strOrder, pageLimit);

            if (this.InvokeRequired)
                dataGridView1.Invoke(new MethodInvoker(delegate ()
            {
                dataGridView1.DataSource = dataTable;
            }));
            else
                dataGridView1.DataSource = dataTable;

            DataGridView1_DataBindComplete(dataGridView1,new EventArgs());

            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate () {
                    pager1.Enabled = true;
                    toolStrip1.Enabled = true;
                }));
            }
            else
            {
                pager1.Enabled = true;
                toolStrip1.Enabled = true;
            }

            return pageLimit.RecordCount;
        }

        private void TodoListManagerTab_Load(object sender, EventArgs e)
        {
            OnThemeChanged(new EventArgs());
            pager1.PageCurrent = 1;
            pager1.Bind();
        }

        private void toolStripButtonRemove_Click(object sender, EventArgs e)
        {
            List<TodoManager.TodoDTO> checkedList = new List<TodoManager.TodoDTO>();
            foreach(DataGridViewRow row in this.dataGridView1.Rows)
            {
                object checkedValue = row.Cells[0].Value;
                int TodoItemIdValue = Convert.ToInt32(row.Cells[1].Value);
                if(checkedValue!=null && checkedValue !=DBNull.Value && Convert.ToBoolean(checkedValue))
                {
                    TodoManager.TodoDTO item = new TodoManager.TodoDTO();
                    item.ID = TodoItemIdValue;
                    item.Name = ((System.Data.DataRowView)row.DataBoundItem)["Name"] + "";
                    item.DeleteSign = Convert.ToInt32(((System.Data.DataRowView)row.DataBoundItem)["DeleteSign"]);
                    checkedList.Add(item);
                }
            }

            int seletedItemType = -1;
            bool allowDeleteCommit = true;

            string messageText = "确定要删除所选事项吗";
            foreach (var item in checkedList)
            {
                if (seletedItemType == -1)
                {
                    seletedItemType = item.DeleteSign.HasValue ? item.DeleteSign.Value : 0;
                }
                if (item.DeleteSign != null && item.DeleteSign.HasValue && item.DeleteSign.Value == 1)
                {
                    messageText = "所选的事项已删除,现在是否要恢复";
                }
                if(seletedItemType!=(item.DeleteSign.HasValue? item.DeleteSign.Value : 0))
                {
                    messageText = "所选的事项状态不一致";
                    allowDeleteCommit = false;
                    break;
                }
                seletedItemType = item.DeleteSign.HasValue ? item.DeleteSign.Value : 0;
            }           

            var dialogResult = new DevelopAssistant.Core.ToolBox.MessageDialog(DevelopAssistant.Core.Properties.Resources.information_32px, messageText, MessageBoxButtons.OKCancel).ShowDialog(this);

            if (!allowDeleteCommit)
                return;

            if (dialogResult == DialogResult.OK)
            {
                if (seletedItemType == 1) //还原
                {
                    serviece.UpdateTodoDeleteSign(checkedList, 0);
                }
                else //删除
                {
                    serviece.UpdateTodoDeleteSign(checkedList, 1);
                }
                
                pager1.Bind();

                mainForm.RefreshScheduleTasks();

            }

        }

        private void toolStripDeleteButton_Click(object sender, EventArgs e)
        {
            List<TodoManager.TodoDTO> checkedList = new List<TodoManager.TodoDTO>();
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                object checkedValue = row.Cells[0].Value;
                int TodoItemIdValue = Convert.ToInt32(row.Cells[1].Value);
                if (checkedValue != null && checkedValue != DBNull.Value && Convert.ToBoolean(checkedValue))
                {
                    TodoManager.TodoDTO item = new TodoManager.TodoDTO();
                    item.ID = TodoItemIdValue;
                    item.Name = ((System.Data.DataRowView)row.DataBoundItem)["Name"] + "";
                    item.DeleteSign = Convert.ToInt32(((System.Data.DataRowView)row.DataBoundItem)["DeleteSign"]);
                    checkedList.Add(item);
                }
            }
            
            if (checkedList.Count > 0)
            {
                var dialogResult = new DevelopAssistant.Core.ToolBox.MessageDialog(DevelopAssistant.Core.Properties.Resources.information_32px, "确定要永久删除选择的数据吗", MessageBoxButtons.OKCancel).ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    bool hasError = false;
                    foreach(var item in checkedList)
                    {
                        if (!serviece.DeleteTodoItemForever(item.ID.ToString()))
                        {
                            hasError = true;
                            break;
                        }
                    }

                    if (hasError)
                    {
                        new DevelopAssistant.Core.ToolBox.MessageDialog(DevelopAssistant.Core.Properties.Resources.information_32px, "删除数据过程中出错", MessageBoxButtons.OK).ShowDialog(this);
                    }
                    else
                    {
                        new DevelopAssistant.Core.ToolBox.MessageDialog(DevelopAssistant.Core.Properties.Resources.information_32px, "删除数据成功", MessageBoxButtons.OK).ShowDialog(this);
                    }
                   
                    pager1.Bind();
                    mainForm.RefreshScheduleTasks();
                }                
            }
            else
            {
                new DevelopAssistant.Core.ToolBox.MessageDialog(DevelopAssistant.Core.Properties.Resources.information_32px, "还未选择数据", MessageBoxButtons.OK).ShowDialog(this);
            }
        }

        private void toolStripAddButton_Click(object sender, EventArgs e)
        {
            var result = new DevelopAssistant.Core.ToolBox.AddTodoForm(mainForm, null).ShowDialog(this);
            if (result == DialogResult.OK)
            {
                pager1.PageCurrent = 1;
                pager1.Bind();
            }
        }

        private void toolStripCheckBoxButton_CheckStateChanged(object sender, EventArgs e)
        {
            NToolStripCheckBox checkBox = (NToolStripCheckBox)sender;
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                row.Cells[0].Value = checkBox.CheckState;
            }
        }

        private void toolStripUpdateButton_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                var dataRowView = (System.Data.DataRowView)dataGridView1.Rows[dataGridView1.SelectedRows[0].Index].DataBoundItem;
                try
                {
                    TodoManager.TodoDTO todoItem = serviece.GetTodoItem(dataRowView["ID"] + "");
                    DateTimeItem item = new DateTimeItem();
                    item.Id = todoItem.ID.ToString();
                    item.Name = todoItem.Name;
                    item.Title = todoItem.Title;
                    item.Summary = todoItem.Summary;
                    item.ResponsiblePerson = todoItem.ResponsiblePerson;
                    item.DateTime = todoItem.DateTime.Value;

                    Timeliness timeliness = Timeliness.Green;
                    //Enum.TryParse(todoItem.Timeliness.Value.ToString(), out timeliness);
                    switch (todoItem.Timeliness.Value)
                    {
                        case 1:
                            timeliness = Timeliness.Green;
                            break;
                        case 5:
                            timeliness = Timeliness.Dark;
                            break;
                        case 6:
                            timeliness = Timeliness.Black;
                            break;
                    }

                    item.Timeliness = timeliness;
                    item.Description = todoItem.Description;

                    var result = new DevelopAssistant.Core.ToolBox.EditTotoForm(mainForm, item).ShowDialog(this);
                    if (result == DialogResult.OK)
                    {
                        pager1.Bind();
                    }
                }
                catch(Exception ex)
                {
                    DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
                }

            }
        }

        public override void OnThemeChanged(EventArgs e)
        {
            switch (AppSettings.EditorSettings.TSQLEditorTheme)
            {
                case "Default":
                    ForeColor = SystemColors.ControlText;
                    BackColor = SystemColors.Control;
                    deleteRowForeColor = System.Drawing.SystemColors.ControlDarkDark;
                    deleteRowBackColor = System.Drawing.SystemColors.ControlLight;
                    toolStrip1.ForeColor = SystemColors.ControlText;
                    toolStrip1.BackColor = SystemColors.Window;                   
                    textBox1.XForeColor = SystemColors.ControlText;
                    textBox1.XBackColor = SystemColors.Window;
                    comboBoxImportState.ForeColor = SystemColors.ControlText;
                    comboBoxImportState.BackColor = SystemColors.Window;
                    comboBoxDeleteState.ForeColor = comboBoxImportState.ForeColor;
                    comboBoxDeleteState.BackColor = comboBoxImportState.BackColor;
                    //toolStripCheckBoxButton.ForeColor = comboBoxImportState.ForeColor;
                    //toolStripCheckBoxButton.BackColor = comboBoxImportState.BackColor;
                    btnQuery.ForeColor = SystemColors.ControlText;
                    btnQuery.BackColor = SystemColors.Control;
                    break;
                case "Black":
                    ForeColor = Color.FromArgb(240, 240, 240);
                    BackColor = Color.FromArgb(030, 030, 030);
                    deleteRowForeColor = Color.FromArgb(120, 120, 120);
                    deleteRowBackColor = Color.FromArgb(030, 030, 030);
                    toolStrip1.ForeColor = Color.FromArgb(240, 240, 240);
                    toolStrip1.BackColor = Color.FromArgb(050, 050, 050);                    
                    textBox1.XForeColor = Color.FromArgb(240, 240, 240);
                    textBox1.XBackColor = Color.FromArgb(030, 030, 030);
                    comboBoxImportState.ForeColor = Color.FromArgb(240, 240, 240);
                    comboBoxImportState.BackColor = Color.FromArgb(030, 030, 030);
                    comboBoxDeleteState.ForeColor = comboBoxImportState.ForeColor;
                    comboBoxDeleteState.BackColor = comboBoxImportState.BackColor;
                    //toolStripCheckBoxButton.ForeColor = comboBoxImportState.ForeColor;
                    //toolStripCheckBoxButton.BackColor = comboBoxImportState.BackColor;
                    btnQuery.ForeColor = Color.FromArgb(240, 240, 240);
                    btnQuery.BackColor = Color.FromArgb(050, 050, 050);
                    break;
            }

            pager1.SetTheme(AppSettings.EditorSettings.TSQLEditorTheme);
            dataGridView1.SetTheme(AppSettings.EditorSettings.TSQLEditorTheme);

            PremityGridView();            
        }

    }
}
